/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.media.AudioManager;
import android.media.IAudioService;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemService;
import android.provider.Settings;
import android.util.Log;

public final class TvSettingsObserverService extends Service {
    private static final String LOG_TAG = "TvSettingsObserverService";

    private static final String ADBD_SERVICE = "adbd";
    private static final String USER_BUILD_TYPE = "user";

    private static final String[] VOLUME_SETTINGS = Settings.System.VOLUME_SETTINGS;

    private ContentResolver mContentResolver;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(LOG_TAG, "onCreate");

        mContentResolver = getContentResolver();

        TvSettingsObserver observer = new TvSettingsObserver(new Handler());

        changeStayOnWhilePluggedInIfNecessary();
        mContentResolver.registerContentObserver(Settings.Global.getUriFor(
                Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
                false, observer);

        changeVolumesIfNecessary();
        for (String volumeSetting : VOLUME_SETTINGS) {
            mContentResolver.registerContentObserver(Settings.System.getUriFor(volumeSetting),
                    false, observer);
        }

        if (android.os.Build.TYPE.equals(USER_BUILD_TYPE)) {
            changeAdbServiceStatusIfNecessary();
            mContentResolver.registerContentObserver(
                    Settings.Global.getUriFor(Settings.Global.ADB_ENABLED),
                    false, new TvSettingsObserverExtraForUserBuild(new Handler()));
        }
    }

    @Override
    public IBinder onBind(Intent arg) {
        return null;
    }

    private void changeStayOnWhilePluggedInIfNecessary() {
        if (Settings.Global.getInt(mContentResolver,
                    Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0) == 0) {
            Log.i(LOG_TAG, "not allow to turn off STAY_ON_WHILE_PLUGGED_IN");
            Settings.Global.putInt(mContentResolver, Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 1);
        }
    }

    private void changeVolumesIfNecessary() {
        IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
        IAudioService service = IAudioService.Stub.asInterface(b);

        for (int streamIndex = 0; streamIndex < VOLUME_SETTINGS.length; streamIndex++) {
            final String settingName = VOLUME_SETTINGS[streamIndex];
            final int defaultValue = AudioManager.DEFAULT_STREAM_VOLUME[streamIndex];

            if (Settings.System.getInt(mContentResolver, settingName, defaultValue) !=
                    defaultValue) {
                Log.i(LOG_TAG, "not allow to change " + settingName);
                try {
                    service.setStreamVolume(streamIndex, defaultValue, 0);

                    // We need to change the value explicitly because restoring a user's account
                    // can change only the value in DB with leaving AudioService as it was.
                    Settings.System.putInt(mContentResolver, settingName, defaultValue);
                    Settings.System.putInt(mContentResolver,
                            settingName + Settings.System.APPEND_FOR_LAST_AUDIBLE,
                            defaultValue);
                } catch (RemoteException ex) {
                    Log.w(LOG_TAG, "Exception changing volume of music", ex);
                }
            }
        }
    }

    private void changeAdbServiceStatusIfNecessary() {
        if (Settings.Global.getInt(mContentResolver, Settings.Global.ADB_ENABLED, 0) > 0) {
            if (SystemService.isStopped(ADBD_SERVICE)) {
                Log.d(LOG_TAG, "ADB is enabled. Running ADB service");
                SystemService.start(ADBD_SERVICE);
            }
        } else {
            if (SystemService.isRunning(ADBD_SERVICE)) {
                Log.d(LOG_TAG, "ADB is disabled. Stopping ADB service");
                SystemService.stop(ADBD_SERVICE);
            }
        }
    }

    private final class TvSettingsObserver extends ContentObserver {
        public TvSettingsObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            changeStayOnWhilePluggedInIfNecessary();
            changeVolumesIfNecessary();
        }
    }

    private final class TvSettingsObserverExtraForUserBuild extends ContentObserver {
        public TvSettingsObserverExtraForUserBuild(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            changeAdbServiceStatusIfNecessary();
        }
    }
}